package com.miniblog.gateway.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.miniblog.common.enums.Constant;
import com.miniblog.common.utils.JwtUtils;
import com.miniblog.common.utils.Msg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;

/**
 * 类名：AuthFilter.java
 * 路径：com.miniblog.gateway.config.AuthFilter.java
 * 创建人：tanyp
 * 创建时间：2019/12/23 14:12
 * 功能：请求认证过滤器
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Value("#{'${auth.skip-auth-urls}'.split(',')}")
    private String[] skipAuthUrls;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 跳过不需要验证的请求
        String url = exchange.getRequest().getURI().getPath();
        if (!Objects.isNull(skipAuthUrls) && Arrays.asList(skipAuthUrls).contains(url)) {
            return chain.filter(exchange);
        }

        String token = exchange.getRequest().getHeaders().getFirst("token");
        ServerHttpResponse response = exchange.getResponse();
        Msg msg = new Msg();
        if (isExpired(token)) {
            return chain.filter(exchange);
        }

        msg.setCode(401);
        msg.setMessage("success");
        msg.setData("Token error or empty");
        byte[] datas = JSON.toJSONString(msg).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(datas);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return -100;
    }

    /**
     * @MethodName： isExpired
     * @Description：验证token
     * @Author： tanyp
     * @Date： 2020/1/14 16:54
     * @Params： [token]
     * @Return： boolean
     * @Reviser：
     */
    private boolean isExpired(String token) {
        if (!Objects.isNull(token) && !Objects.equals("", token) ) {
            String userId = JwtUtils.verifyToken(token);
            Object userInfo = redisTemplate.opsForValue().get(Constant.TOKEN_KEY.getMessage() + userId);
            if(!Objects.isNull(userInfo)){
                JSONObject userJson = JSON.parseObject(String.valueOf(userInfo));
                String _token = String.valueOf(userJson.get("token"));
                if(Objects.equals(token, _token)){
                    return true;
                }
            }
        }
        return false;
    }

}
